package serverx

import (
	"regexp"
	"strings"

	"gitee.com/workits/pkgs/contextx"
	"gitee.com/workits/pkgs/errorx"
	"gitee.com/workits/pkgs/jwtx"
	"gitee.com/workits/pkgs/logx"
	"github.com/gin-gonic/gin"
)

// WithJWT 返回JWT Handler
func WithJWT(cfg Config, jwtCfg jwtx.Config) gin.HandlerFunc {
	return func(ctx *gin.Context) {
		// 处理被忽略的请求
		path := ctx.Request.URL.Path
		for _, v := range cfg.NonAuth {
			if strings.Contains(v, "*") {
				reg := "^" + strings.Replace(v, "*", "(.+)", -1) + "$"
				if match, err := regexp.Match(reg, []byte(path)); err == nil && match {
					ctx.Next()
					return
				}
			} else {
				if v == path {
					ctx.Next()
					return
				}
			}
		}

		// 验证token
		ustring, err := jwtx.VerifyRequest(jwtCfg, ctx.Request)
		if err != nil {
			logx.Warnf(err.Error(), ctx.Request.Context())
			RenderError(ctx, errorx.ErrAPIUnauthorized)
			return
		}

		// 获取user info放到context中
		ctx.Request = ctx.Request.WithContext(contextx.WithTraceUser(ctx.Request.Context(), ustring))
		ctx.Next()
	}
}
